#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <QTcpServer>
#include <QTcpSocket>
#include <QHostAddress>
#include <QByteArray>
#include <QDataStream>
#include <QSqlQuery>
#include <QDateTime>
#include <QJsonObject>
#include <QJsonDocument>
#include <QSqlError>
void MainWindow::InitAll()
{
    this->setCentralWidget(ui->plainTextEdit);
    InitTCP();
}

void MainWindow::InitTCP()
{
    tcpServer=new QTcpServer(this);
    tcpSocket=new QTcpSocket(this);
    QHostAddress address=QHostAddress::AnyIPv4;
    tcpServer->listen(address,loginPort);
    ui->plainTextEdit->appendPlainText("listening address:"+QString::number(QHostAddress::AnyIPv4));
    ui->plainTextEdit->appendPlainText("listening prot:"+QString::number(loginPort));

    connect(tcpServer,&QTcpServer::newConnection,this,&MainWindow::do_newConnection);
}

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    InitAll();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_actionClear_triggered()
{
    ui->plainTextEdit->clear();
}

void MainWindow::do_newConnection()
{
    tcpSocket=tcpServer->nextPendingConnection();
    connect(tcpSocket,&QTcpSocket::readyRead,this,&MainWindow::do_readyRead);
}

void MainWindow::do_readyRead()
{
    QDateTime dateTime=QDateTime::currentDateTime();
    QByteArray data=tcpSocket->readAll();
    //check id if exist
    QJsonDocument doc=QJsonDocument::fromJson(data);
    if(!doc.isNull()&&doc.isObject()){
        QJsonObject jsonRoot=doc.object();
        if(jsonRoot.contains("type")){
            QString strType=jsonRoot["type"].toString();
            if(strType=="IDIfExist"){//check id if exist
                ui->plainTextEdit->appendPlainText(dateTime.toString("yyyy-MM-dd hh:mm:ss"));
                ui->plainTextEdit->appendPlainText("type:"+strType);
                ui->plainTextEdit->appendPlainText("ID:"+jsonRoot["ID"].toString());
                QSqlQuery query;
                query.prepare("SELECT * FROM userTable WHERE ID=:ID");
                query.bindValue(":ID",jsonRoot["ID"].toString());
                if(!query.exec()){
                    ui->plainTextEdit->appendPlainText("sql fielded!!!");
                }
                bool exist=false;
                if(query.next()){
                    ui->plainTextEdit->appendPlainText("!!!");
                    exist=true;
                }

                QJsonObject jsonObject;
                jsonObject["type"]="IDIfExist";
                if(exist){
                    jsonObject["exist"]="true";
                    ui->plainTextEdit->appendPlainText("true\n");
                }else{
                    ui->plainTextEdit->appendPlainText("false\n");
                    jsonObject["exist"]="false";
                }
                tcpSocket->write(QJsonDocument(jsonObject).toJson());
            }else if(strType=="addUser"){
                int ID=jsonRoot["ID"].toString().toInt();
                QString username=jsonRoot["username"].toString();
                QString password=jsonRoot["password"].toString();
                QSqlQuery addQuery;
                addQuery.prepare("INSERT INTO userTable VALUES(?,?,?);");
                addQuery.addBindValue(ID);
                addQuery.addBindValue(username);
                addQuery.addBindValue(password);
                if(addQuery.exec()){
                    jsonRoot["background"]="createOk";
                    ui->plainTextEdit->appendPlainText(dateTime.toString("yyyy-MM-dd hh:mm:ss"));
                    ui->plainTextEdit->appendPlainText(QString::number(ID)+"createOK");
                }else{
                    jsonRoot["background"]="createNotOk";
                    ui->plainTextEdit->appendPlainText(dateTime.toString("yyyy-MM-dd hh:mm:ss"));
                    ui->plainTextEdit->appendPlainText(QString::number(ID)+"createNotOK");
                    ui->plainTextEdit->appendPlainText("error:"+addQuery.lastError().text());
                }
                tcpSocket->write(QJsonDocument(jsonRoot).toJson());
            }
        }
        return;
    }
    //get Login user and pswd
    QDataStream aStream(&data,QIODevice::ReadOnly);
    QString user,pswd;
    aStream>>user>>pswd;
    ui->plainTextEdit->appendPlainText(dateTime.toString("yyyy-MM-dd hh:mm:ss"));
    ui->plainTextEdit->appendPlainText("user:"+user);
    ui->plainTextEdit->appendPlainText("pswd:"+pswd);

    //check userand pswd from database
    QSqlQuery checkQuery;
    checkQuery.prepare("SELECT * FROM userTable WHERE ID=:ID");
    checkQuery.bindValue(":ID",user.toInt());
    checkQuery.exec();

    while(checkQuery.next()){
        if(pswd==checkQuery.value(2).toString()){
            QByteArray dt;
            QDataStream stream(&dt,QIODevice::WriteOnly);
            QString str("Login");
            ui->plainTextEdit->appendPlainText(str+"\n");
            stream<<QString(str);
            tcpSocket->write(dt);
            return ;
        }
    }
    QByteArray dt;
    QDataStream stream(&dt,QIODevice::WriteOnly);
    QString str("Login Field!!!");
    ui->plainTextEdit->appendPlainText(str+"\n");
    stream<<QString(str);
    tcpSocket->write(dt);
}

